<template>
  <el-container>
    <el-header>聊天室</el-header>
    <el-main>
      <!-- <el-input placeholder="请输入内容" v-model="searchInput">
        <el-button slot="append" icon="el-icon-search"></el-button>
      </el-input> -->
      <el-button type="primary" v-on:click="addRoomDialogVisible = true">新建聊天室</el-button>
      <br /><br />

      <el-table class="roomTable" :data="tableData" style="width: 100%" :show-header="false" @cell-click="handle">
        <el-table-column prop="roomName"></el-table-column>
        <el-table-column width="50%">
          <template slot-scope="scope">
            <el-badge :hidden="scope.row.unreaMessage == 0 ? true : false" :value="scope.row.unreaMessage" class="item">
            </el-badge>
          </template>
        </el-table-column>
      </el-table>


      <!--  新建聊天室 dialog -->
      <el-dialog title="新建聊天室" :visible.sync="addRoomDialogVisible" width="80%" :before-close="handleCloseAddRoomDialog">

        <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="聊天室名称" prop="roomname">
            <el-input type="roomname" v-model="ruleForm.roomname"></el-input>
          </el-form-item>
          <el-form-item label="聊天室备注">
            <el-input type="roomremarks" v-model="ruleForm.roomremarks"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

    </el-main>
    <el-footer>
      <el-row type="flex" class="row-bg">
        <el-col :span="12">
          <div class="grid-content bg-purple div-msg"><a class="btn1">聊天室</a></div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content bg-purple div-self"><a class="btn2" v-on:click="goSelf()">我的</a></div>
        </el-col>
      </el-row>
    </el-footer>
  </el-container>
</template>

<script>
  import {
    checkResData
  } from '../utils/selfInfoUtil.js'
  export default {
    // name: 'Home',
    data() {
      return {
        searchInput: '',
        tableData: [],
        addRoomDialogVisible: false,
        ruleForm: {
          roomname: '',
          roomremarks: ''
        },
        rules: {
          roomname: [{
            required: true,
            message: '聊天室名称不能为空!',
            trigger: 'change'
          }]
        }
      }
    },
    created() {
      if (location.href.indexOf("#reloaded") == -1) {
        location.href = location.href + "#reloaded";
        location.reload();
        return
      }
      this.getRoomList()
      this.connectWebSocket()
    },
    methods: {
      //获取用户加入的聊天室列表
      getRoomList() {
        this.$axios.post('/room/user/rooms')
          .then(res => {
            if (checkResData(res.data.code, res.data.success)) {
              if (res.data.data.length == 0) {
                // this.$message.info("获取数据成功，当前用户没有加入聊天室")
              } else {
                // this.$message.success(res.data.msg)
                this.tableData = res.data.data
              }
            } else {
              this.$message.error(res.data.msg)
            }
          })
          .catch(err => {
            this.$message.error("服务器溜了！ 已经去抓了")
          })
      },
      // 点击聊天室，就跳转到该聊天室的聊天界面，以下是路由所携带的参数
      handle(row, column, event, cell) {
        this.$router.push({
          name: 'ChattingRoom',
          params: {
            roomid: row.id,
            roomname: row.roomName,
            msgCount: row.unreaMessage
          }
        })
      },
      handleCloseAddRoomDialog(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$axios.post('/room/create', {
                roomName: this.ruleForm.roomname,
                roomRemarks: this.ruleForm.roomremarks
              })
              .then(res => {
                if (checkResData(res.data.code, res.data.success)) {
                  this.$message.success(res.data.msg)
                  this.addRoomDialogVisible = false
                  this.getRoomList()
                } else {
                  this.$message.info(this.data.msg)
                }
              })
              .catch(err => {
                this.$message.error("服务器溜了！ 已经去抓了")
              })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      // 建立websocket连接
      connectWebSocket() {
        var socket;
        var _this = this;
        if (typeof(WebSocket) == "undefined") {
          console.log("您的浏览器不支持 WebSocket!");
        } else {
          console.log("您的浏览器支持 WebSocket!");
          socket = new WebSocket("ws://192.168.5.13:8002/websocket/room/monitorrooms");
          socket.onopen = function() {
            console.log("Home Websocket 已打开");
            socket.send("这是来自客户端的消息" + location.href + new Date());
          };
          socket.onmessage = function(msg) {
            var strJson = JSON.parse(msg.data)
            console.log("msg", strJson)
            for (var i = 0; i < _this.tableData.length; i++) {
              if (_this.tableData[i].id == strJson.reveId) {
                _this.tableData[i].unreaMessage += 1
              }
            }
            // console.log(_this.tableData)
          }
          socket.onclose = function() {
            console.log("Home Websocket 已经关闭")
          }
          socket.onerror = function() {
            alert("Home Websocket 发生了错误")
          }
        }
      },
      goSelf() {
        this.$router.push(`self`)
      }
    }
  }
</script>

<style scoped="scoped">
  .el-footer,
  .el-header {
    text-align: center;
    background-color: #B3C0D1;
    color: #333;
    line-height: 3.75rem;
  }

  .el-main {
    background-color: #E9EEF3;
    color: #333;
  }

  .el-container {
    padding: 0;
    margin: 0;
    min-height: 100vh;
    background-color: #0077AA;
  }

  .div-msg {
    color: #158bb8;
    font-size: 1.125rem;
  }

  .div-self {
    color: white;
    font-size: 100%;
  }

  .btn1,
  .btn2,
  .roomTable {
    cursor: pointer;
  }

  .box {
    position: relative;
    width: 10rem;
    height: 10rem;
    margin: 2rem auto;
    box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
  }
</style>
